# -*- coding: utf-8 -*-

# Copyright (c) 2010, Nik S Denin <wolf.step@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
#   this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
#   this list of conditions and the following disclaimer in the documentation
#   and/or other materials provided with the distribution.
# * Neither the name of Nik S Denin nor the names of its contributors
#   may be used to endorse or promote products derived from this software
#   without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

from PyQt4.QtCore import Qt, QTimer, SIGNAL, QString
from PyQt4 import QtGui
from PyQt4.QtGui import QGraphicsLinearLayout
from PyKDE4.plasma import Plasma
from PyKDE4 import plasmascript
from PyKDE4.kdeui import KWallet
from PyKDE4.kdeui import KPageDialog, KDialog

from settings import SettingsDialog
import plurk

class PlasmaPlurk(plasmascript.Applet):
	def __init__(self, parent, args=None):
		plasmascript.Applet.__init__(self,parent)

	def init(self):
		self.setHasConfigurationInterface(True)
		self.setAspectRatioMode(Plasma.IgnoreAspectRatio)
		self.setBackgroundHints(Plasma.Applet.DefaultBackground)
		
		self.layout = QGraphicsLinearLayout(Qt.Vertical, self.applet)

		self.label = Plasma.Label(self.applet)
		self.label.setText(QtGui.QApplication.translate("Applet", "Configure plasmoid", None, QtGui.QApplication.UnicodeUTF8))
		self.label.setAlignment(Qt.AlignCenter)
		self.layout.addItem(self.label)
		self.applet.setLayout(self.layout)

		self.settings_dialog = None
		self.settings = {"login": None, "password": None}
		
		self.plurk = plurk.plurk()

		self.wallet = KWallet.Wallet.openWallet(KWallet.Wallet.LocalWallet(),  0, 1)
		if self.wallet:
			self.connect(self.wallet, SIGNAL("walletOpened(bool)"), self.walletOpened)

		self.timer = QTimer()
		self.connect(self.timer, SIGNAL("timeout(bool)"), self.loadPlurks)

	def postInit(self):
		self.timer.start(1000 * 10) # update plurks every 10 seconds
		self.loadPlurks()

	def showConfigurationInterface(self):
		self.settings_dialog = SettingsDialog(self)
		dialog = KPageDialog()
		dialog.setFaceType(KPageDialog.Plain)
		dialog.setButtons(KDialog.ButtonCode(KDialog.Ok | KDialog.Cancel))
		dialog.addPage(self.settings_dialog, u"Plurk settings")
		self.connect(dialog, SIGNAL("okClicked()"), self.configAccepted)
		self.connect(dialog, SIGNAL("cancelClicked()"), self.configDenied)
		dialog.resize(350, 200)
		dialog.exec_()

	def configAccepted(self):
		login = self.settings["login"]
		password = self.settings["password"]
		if login is not None and password is not None:
			if len(login) > 0 and len(password) > 0:
				self.settings = self.settings_dialog.getSettings()
				wallet = KWallet.Wallet.openWallet(KWallet.Wallet.LocalWallet(), 0)
				if wallet:
					if not wallet.hasFolder("plasmaplurk"):
						wallet.createFolder("plasmaplurk")
					wallet.setFolder("plasmaplurk")
					for e in wallet.entryList():
						wallet.removeEntry(e)
					wallet.writePassword(login, password)
					self.postInit()

	def configDenied(self):
		pass

	def walletOpened(self):
		if not self.wallet.hasFolder("plasmaplurk"):
			self.wallet.createFolder("plasmaplurk")
		self.wallet.setFolder("plasmaplurk")

		if self.wallet.entryList().isEmpty():
			self.update(QtGui.QApplication.translate("Applet", "Configure plasmoid", None, QtGui.QApplication.UnicodeUTF8))
		else:
			login = str(self.wallet.entryList().first())
			password = QString()
			self.wallet.readPassword(login, password)
			self.update_settings(login, password)
			self.postInit()

	def update_settings(self, login, password):
		self.settings = {"login": login, "password": password}

	def loadPlurks(self):
		print "Load plurks!"

	def update(self, message):
		self.label.setText(message)

def CreateApplet(parent):
	return PlasmaPlurk(parent)
